<template>
  <div class="common-list-container__v2" v-loading.fullscreen.lock="loading">
    <div class="common-list-header__v2">
      <div>
        <el-input class="search-input" placeholder="请输入工单编号/客户信息" v-model="searchParams.keyword">
          <el-button class="search-input__append" slot="append" @click="search">搜索</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">重置</el-button>
      </div>
      <span class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
        <i class="iconfont icon-filter" @click.self="panelSearchAdvancedToggle"></i>
        高级搜索
      </span>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2">
        
        <div class="common-list-view-header__v2-left">
          <!-- start 新建计划任务按钮 -->
          <el-dropdown v-if="allowTaskAdd">
            <el-button type="primary" icon="el-icon-plus">新建计划任务</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(taskType, index) in taskTypes"
                :key="index"
              >
                <div @click="createPlanTask(taskType)">
                  {{ taskType.name }}
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- end 新建计划任务按钮 -->
          
          <!-- start 删除按钮 -->
          <div
            class="task-list-del task-font14 task-c06 cur-point mar-l-12"
            v-if="allowTaskEditAll"
            @click="deletePlanTaskHandler"
          >
            <i class="iconfont icon-delete task-icon"></i>
            删除
          </div>
          <!-- end 删除按钮 -->
        </div>
        
        <div class="common-list-view-header__v2-right">
          <!-- start 选择列 -->
          <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
            选择列
            <i class="iconfont icon-fdn-select"></i>
          </span>
          <!-- end 选择列 -->
          
          <!-- start 更多操作按钮 -->
          <el-dropdown v-if="allowExport && isButtonDisplayed">
            <div 
              class="task-ai task-flex task-font14 task-c6 task-pointer cur-point mar-l-16"
              @click="trackEventHandler('moreAction')"
            >
              <span class="task-mr4 task-ml4">更多操作</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportPlanTask(false)">导出</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed"> 
                <div @click="exportPlanTask(true)">导出全部</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- end 更多操作按钮 -->
        </div>
        
      </div>
      <div
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        已选择
        <span>
          {{ multipleSelection.length }}
        </span>
        条
        <span class="pointer" @click="toggleSelection">清空</span>
      </div>
      <!--s 表格 -->
      <el-table
        ref="table"
        class="common-list-table__v2 mt_8"
        stripe
        :data="taskPage.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
      >
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
        ></el-table-column>
        <el-table-column
          v-for="column in columns"
          v-if="column && column.show"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div class="common-list-table-footer__v2 mt_12">
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          :layout="defaultTableData.defaultLayout"
          :total="taskPage.totalElements"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="search"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
    </base-search-drawer>
    <!-- 选择列 --> 
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    
    <!-- start 导出工单 -->
    <base-export
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :validate="checkExportCount"
      method="post"
      :action="taskListExport"
    />
    <!-- end 导出工单 -->
  </div>
</template>

<script>
// api
import{ getTaskTypesMap, getAllFields, deletePlanTask, getPlanTaskList } from '@src/api/TaskApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields} from './fields';
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';

import formatColumn from 'packages/BaseTableCell/formatColumn'
/* util */
import Log from '@src/util/log.ts'
import { formatDate } from 'pub-bbx-utils'
import { checkButtonDisplayed } from '@src/util/dom';
import { defaultTableData } from '@src/util/table'
/* export & import */
import {taskListExport} from '@src/api/Export'
import { safeNewDate } from '@src/util/time';

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

const MAXCHECK = 500;

// 埋点事件对象
const TRACK_EVENT_MAP = {
  search: 'pc：工单计划任务列表-搜索事件',
  moreAction: 'pc：工单计划任务列表-更多操作事件',
  reset: 'pc：工单计划任务列表-重置事件',
  avvancedSearch: 'pc：工单计划任务列表-高级搜索事件',
  columns: 'pc：工单计划任务列表-选择列事件',
};

export default {
  name: 'task-plan-task-list',
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      currentTaskType: {},
      taskTypes: [],
      taskFields: [],
      multipleSelection: [],

      searchParams: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        sorts: []
      },
      taskPage: new Page(),

      visible: false,
      columns: getColumnFields(this),
      columnNum: 1,

      loading: false,
      initData: {},
      taskListExport
    }
  },
  computed: {
   
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        ...this.taskFields.filter(filed => { // 过滤重复项
          return !getColumnFields(this).some(item => item.field === filed.fieldName);
        })
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    auth() {
      return this.initData?.auth || {}
    },
    allowTaskAdd() {
      return Boolean(this.auth.TASK_ADD)
    },
    allowTaskEditAll() {
      return this.auth?.TASK_EDIT === 3
    },
    allowExport() {
      return this.auth?.TASK_EXPORT
    },
    exportColumns() {
      return (
        this.columns.map(column => {
          column.export = true
          return column
        })
      )
    },
    selectedPlanTaskIds() {
      return this.multipleSelection.map(planTask => planTask.id)
    },
    taskTypeList() {
      return [
        {
          name: '全部', templateId: ''
        },
        ...this.taskTypes
      ]
    }
  },
  watch: {
    taskFields() {
      this.columns = [
        ...getColumnFields(this),
        ...this.taskFields.filter(f => {
          return f.isSystem !== 1 
          && !['attachment', 'separator', 'info', 'autograph'].includes(f.formType)
        })
      ].map(field => {
        return {
          ...formatColumn(field),
          field: field.field || field.fieldName
        }
      });
    },
    'currentTaskType.id': {
      handler(newVal, oldVal) {
        if(newVal && newVal != oldVal) {
          this.fetchTaskFields();
        }
      }
    }
  },
  methods: {
    /**  获取工单类型 */
    fetchTaskTypesMap() {
      // 如果工单类型列表数据已存在则不查询
      if (this.taskTypes.length > 0) return
      
      return (
        getTaskTypesMap().then((data) => {
          let isSuccess = data.success
          if (!isSuccess) return
        
          this.taskTypes = data?.result || []
          // key : 工单类型id(string) -> value: TaskType
          this.taskTypesMap = (
            this.taskTypes
              .reduce((acc, currentTaskType) => {
                acc[currentTaskType.templateId] = currentTaskType
                return acc
              }, {})
          )
        }).catch(err => {
          console.error(err)
        })
      )
    },
    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：工单ji列表-高级搜索事件');
      this.visible = true;
    },
    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },
    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          field.show = true;
        });
        this.taskFields = result;
      }).catch(err => {
        console.error(err);
      });
    },
    /** 获取列表数据 */
    fetchTaskList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }
      
      console.log('搜索参数: ', params);
      
      this.loading = true
      
      getPlanTaskList(params)
        .then((res) => {
          this.loading = false;
          this.taskPage = res?.result || {}
        })
        .catch(err => {
          this.loading = false;
          console.error(err);
        })
    },
    /** 搜索事件 */
    search () {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      
      if(advancedSearchParams.taskType) {
        let typeId = advancedSearchParams.taskType;
        let taskType = this.taskTypes.find(item => item.templateId === typeId);
        this.currentTaskType = {
          id: typeId,
          name: taskType && taskType.name
        };
      }

      this.fetchTaskList(advancedSearchParams);
      this.closeDrawer();
    },
    /** 打开选择列 */
    showAdvancedSetting(){
      window.TDAPP.onEvent('pc：关闭工单列表-选择列事件');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /** 选择列更新事件 */
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.$message.success(this.$t('common.base.saveSuccess'));
      })
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    /** 表格选择操作 */
    handleSelection(selection) {
      // zr_todo:
      this.multipleSelection = selection;
      // return this.$platform.alert(`最多只能选择${MAXCHECK}条数据`);
    },
    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      this.searchParams.sorts = [{
        property: column.isSystem ? prop : `attribute.${prop}`,
        direction: order === 'ascending' ? 'ASC' : 'DESC',
      }]
      this.search();
    },
    /** 选择框 zr_todo */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },
    /** 页码跳转 */
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.taskPage.list = [];
      this.search();
    },
    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;
      
      this.search();
    },
    createPlanTask(taskType = {}) {
      const templateId = taskType?.templateId || ''
      const fromId = window.frameElement?.getAttribute('id')
      
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateTask,
        titleKey: '新建计划任务',
        params: `defaultTypeId=${templateId}`,
        fromId
      })
    },
    async deletePlanTaskHandler() {
      if (this.selectedPlanTaskIds.length <= 0) {
        return this.$platform.alert('请选择需要删除的数据')
      }
      
      try {
        const confirm = await this.$platform.confirm('确定要删除所选计划任务吗？')
        if (!confirm) return
        
        this.loading = true
        
        const params = { ids: this.selectedPlanTaskIds || [] }
        const result = await deletePlanTask(params) || {}
        const success = result.succ
        if (!success) {
          return this.$platform.alert(result?.message || '')
        }
        
        this.$platform.alert('删除成功')
        this.multipleSelection = []
        this.fetchTaskList()
        
      } catch (error) {
        Log.error(error, this.deletePlanTask.name)
      } finally {
        this.loading = false
        window?.TDAPP?.onEvent('pc：工单计划任务列表-删除计划任务')
      }
    },
    /**
     * @description TalkingData事件埋点
     * @param {String} type The constant TRACK_EVENT_MAP of the keys
    */
    trackEventHandler(type = '') {
      let eventName = TRACK_EVENT_MAP[type]
      if (!eventName) return
      
      window?.TDAPP?.onEvent(eventName)
    },
    /**
     * @description 导出工单
     * @param {Boolean} exportAll 是否导出全部
     */
    exportPlanTask(exportAll) {
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}工单计划任务数据.xlsx`
      
      if (!exportAll && this.selectedPlanTaskIds.length <= 0) {
        return this.$platform.alert('请选择要导出的数据')
      }
      
      const planTaskIds = exportAll ? [] : this.selectedPlanTaskIds
      this.$refs.exportPanel.open(planTaskIds, fileName);
    },
    /**
     * @description 导出提示
    */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message)
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0
      
      return (
        exportAll && this.taskPage.totalElements > max
          ? '为了保障响应速度，暂不支持超过5000条以上的数据导出，请您分段导出。'
          : null
      )
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedArray, ids) {
      // 
    }
  },
  mounted() {
    // 获取工单类型列表
    this.fetchTaskTypesMap();
    this.fetchTaskList();
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell
  }
}
</script>

<style lang="scss" scoped>
.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}
</style>